'use strict';

var news_c = db.collection('news');

class News {
    constructor(info) {
        if (info) {
            let self = this;
            // id
            self.id = 'news_' + Math.random().toString(16).substr(2, 2) + (+new Date).toString(16);
            // title
            self.title = info.title;
            self.content = info.content;
            self.preview_url = info.preview_url;
            self.viewtotal = info.viewtotal || 0;
            self.createtime = +new Date;
        }
    }

    save() {
        let self = this;
        printData('正在创建资讯:', self);
        if (!self.title) {
            return printError('资讯标题不可为空');
        }
        if (!self.content) {
            return printError('资讯内容不可为空');
        }
        if (!self.preview_url) {
            return printError('资讯预览图不可为空');
        }
        return co(function* () {
            var res = yield mongo.insertOne(news_c, self);
            self._id = res.insertedId;
            return self;
        }).catch(e => {
            printError(e);
        });
    }

    static update(news) {
        printData('正在更新资讯:', news);
        return co(function* () {
            var _id = news._id;
            var doc = yield mongo.findOneByObjectId(news_c, _id)
            if (!doc) {
                return printError('资讯不存在');
            }
            delete news._id;
            var res = yield mongo.findOneAndUpdateByObjectId(news_c, {
                _id: _id,
                data: news
            });
            return res.value;
        }).catch(e => {
            printError(e);
        });
    }

    static list(info) {
        printData('正在获取资讯列表:', info);
        return co(function* () {
            var list = yield mongo.find(news_c, {
                limit: info.num,
                skip: info.num * info.page,
                sort: {
                    createtime: -1
                }
            });
            return list;
        }).catch(e => {
            printError(e);
        })
    }

    static detail(_id) {
        printData('正在获取资讯详情：', _id);
        return co(function* () {
            var doc = yield mongo.findOneByObjectId(news_c, _id);
            if (!doc) {
                return printError('资讯内容不存在或已被删除');
            }
            return doc;
        }).catch(e => {
            printError(e);
        });
    }

    static delete(_id) {
        return co(function* () {
            var doc = yield mongo.deleteOneByObjectId(news_c, {
                _id: _id
            });
            return doc;
        }).catch(e => {
            printError(e);
        });
    }

    static count() {
        printData('正在获取资讯统计');
        return co(function* () {
            var count = yield mongo.count(news_c);
            return count;
        }).catch(e => {
            printError(e);
        })
    }
}

module.exports = News;